import os
import csv
import json
from math import ceil
from geopy import distance
from geopy.distance import geodesic
from gps2grid import SpatialRegion


def get_valid_blk(i):
    col_num = 338

    blk = set({i, i+1, i-1, i+col_num, i+col_num+1,i+col_num-1,i-col_num,i-col_num+1,i-col_num-1})
    if i % col_num == 1:
        blk = blk - set({i-1, i-1-col_num, i-1+col_num})
    if i % col_num == 0:
        blk = blk - set({i+1, i+1-col_num, i+1+col_num})
    return list(blk)

def place2grid(SR):
    blk_info = {}
    cnt = -1
    with open("./place/1min_100m1.csv", "r") as f:
        reader = csv.reader(f)
        for gps in reader:
            lat = float(gps[0])
            lon = float(gps[1])
            blk = SR.coord2cell(lat, lon)
            
            if not blk_info.__contains__(blk):
                blk_info[blk] = []
            cnt += 1
            blk_info[blk].append((lat, lon, cnt))

    json_data = json.dumps(blk_info, indent = 4)
    
    with open('./place/1min_200grid.json', 'w') as f2:
        f2.write(json_data)


def gps2place(gps_point, places, place_grid, SR, min_dis):
    blk_id = SR.coord2cell(gps_point[0], gps_point[1])
    blks = get_valid_blk(blk_id)
    flag = False
    for blk in blks:
        bi = str(blk)
        if not place_grid.__contains__(bi):
            continue
        else:
            flag = True
            for item in place_grid[bi]:
                place = (item[0], item[1])
                place_id = item[2]
                dis = geodesic(gps_point, place)
                if dis < min_dis:
                    min_dis = dis
                    target_id = place_id

    if not flag:
        for i in range(len(places)):
            dis = geodesic(gps_point,places[i])
            if dis < min_dis:
                min_dis = dis
                target_id = i+1
    
    return target_id

def dump2place(SR):
    places = []
    min_dis = geodesic((41.4459657, 11.7531545505395), (42.302192553508, 12.9634722613942))
    with open("./place/1min_100m1.csv", "r") as f:
        reader = csv.reader(f)
        for gps in reader:
            places.append((float(gps[0]), float(gps[1])))
    with open('./place/1min_200grid.json') as bf:
        place_grid = json.load(bf)
 
    for i in range(400):
        filename = './trajectory/' + "ID_" +str(i) + '.csv'
        filename2 = './place/1min_100m/'+str(i)+'.csv'
        if not os.path.exists(filename):
            pass
        else:
            print(i)
            with open(filename, "r") as f:
                reader = csv.reader(f)
                tra_places = []
                for trajectories in reader:
                    tra_place = []
                    for trajectory in trajectories:
                        trajectory = trajectory.strip(')').strip('(').split(',')
                        gps = (float(trajectory[0]), float(trajectory[1]))
                        pid = gps2place(gps, places,place_grid,SR,min_dis)
                        tra_place.append(pid)
                    tra_places.append(tra_place)
                    print(i,'_', len(tra_places))
            
            with open(filename2, 'w', newline='') as csvfile:
                spamwriter = csv.writer(csvfile)
                for item in tra_places:
                    spamwriter.writerow(item)


if __name__ == '__main__':
    SR = SpatialRegion(41.4459657, 11.7531545505395, 42.302192553508, 12.9634722613942,300,300,1)
    place2grid(SR)
    dump2place(SR)
